import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import HomeView from '../views/HomeView.vue'

import store from '@/store'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/set',
    name: 'set',
    component: () => import('../views/my/components/set.vue')
  },
  {
    path: '/my',
    name: 'my',
    component: () => import('../views/my/index.vue')
  },
  {
    path: '/detail',
    name: 'detail',
    component: () => import('../views/home/homeListComponent.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  },
  {
    path: '/chat',
    name: 'chat',
    component: () => import('../views/second/chatComponent.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes
})
let arr: string[] = ['/login']

router.beforeEach((to, from, next) => {
  /**
   * 1.to 跳转至的页面
   * 2.from 之前的页面Path
   * 3.next 放行 =》只有执行了next 页面才会被放行渲染
   */
  //用于后续 判断是否登录 1. 判断用户是否登录是吧？
  let token = localStorage.getItem("token")

  if (store.getters["userInfo/getToken"] || token) {
    //登录
    next()
  } else {
    if (arr.includes(to.fullPath)) {
      next() //防止死循环
    }
    next("/login")
  }
})

export default router
